// 创建一个web 服务器来接收压缩后得数据并将其解压到一个文件夹

let http = require('http'),
fs = require('fs'),
zlib = require('zlib');

let server = http.createServer().listen(3000)

server.on('request', (req, res) => {
  let method = req.method
  console.log(method)
  if(req.method == 'POST'){
    let chunks = []
    req.on('data', (chunk) => {
      chunks.push(chunk)
    })
   
    req.on('end', () => {
      let buf = Buffer.concat(chunks)

      zlib.unzip(buf, (err, res) => {
        if(err){
          res.writeHead(500)
          res.end()
          return console.log('ERROR:', err)
        }

        let timestamp = Date.now()
        let filename = `./done${timestamp}.png`
        fs.createWriteStream(filename).write(res)
      })

      res.writeHead(200, {'Content-Type': 'text/plain'})
      res.end('解压并保存')
    })
  }else{
    res.writeHead(200, {'Content-Type': 'text/plain'})
    res.end('other method:' + method)
  }
})

console.log('server runin on 3000.....')
